//
//  RBShopApplyPageStep4VC.m
//  zhongzhenglu
//
//  Created by mac on 2022/10/24.
//

#import "RBShopApplyPageStep4VC.h"
#import "RBDefine.h"
#import "UIView+RBAdd.h"
#import "UIScrollView+RBAdd.h"
#import "RBThemeConfig.h"
#import <Masonry.h>
#import "RBNavigationBar.h"
#import "RBTextField.h"
#import "UIButton+RBAdd.h"
#import <UIColor+YYAdd.h>
#import "UIViewController+RBAdd.h"
#import <UINavigationController+FDFullscreenPopGesture.h>
#import "RBGradientView.h"
#import "RBGrowablePhotoContainer.h"
#import "RBUploadTool.h"
#import "RBURLConfig.h"
#import "RBShopApplyCatResponse.h"

@interface RBShopApplyPageStep4VC ()<UIDocumentInteractionControllerDelegate>

@property(nonatomic, strong) RBNavigationBar *navigationBar;
@property(nonatomic, strong) RBGrowablePhotoContainer *photoContainer;
@property(nonatomic, strong) RBUploadTool *uploadTool;

@property (nonatomic,strong)UIDocumentInteractionController * document;

@property (nonatomic, copy) NSString *contract_path;

@end

@implementation RBShopApplyPageStep4VC

#pragma mark - Lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setup];
    [self getData];
    [self fillData];
}

#pragma mark - Private

- (void)setup
{
    self.fd_prefersNavigationBarHidden = YES;
    RBGradientView *topBgView = [RBGradientView gradientViewWithColors:@[[UIColor colorWithHexString:@"#CADCFF"],[UIColor colorWithHexString:@"#E8F0FF"]] locations:nil vertical:YES];
    [self.view addSubview:topBgView];
    [topBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.height.mas_equalTo(kRBStatusBarHeight + kRBNavigationBarHeight + Zoom(150));
    }];
    self.navigationBar.hidden = NO;
    
    if(self.response.data.status == 2)
    {
        UIAlertController *vc = [UIAlertController alertControllerWithTitle:@"审核失败,请重新提交" message:self.response.data.fail_reason preferredStyle:UIAlertControllerStyleAlert];
        [vc addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [self presentViewController:vc animated:YES completion:nil];
    }
}

- (void)fillData
{
    UIView *statusView = ({
        UIView *view = UIView.new;
        NSArray *imgs = @[@"shopApplyPass",@"shopApplyPass",@"shopApplyPass",@"shopApplyPass",@""];
        NSArray *names = @[@"注册成功",@"审核通过",@"财务审核",@"保证金审核",@"合同审核"];
        for (NSInteger i = 0; i < imgs.count; i++)
        {
            [view h_view_addView:({
                UIView *view = UIView.new;
                [view view_addView:({
                    UIView *view = UIView.new;
                    view.backgroundColor = [UIColor colorWithHexString:@"#518CFF"];
                    [view rbSetCornerRadius:Zoom(19)];
                    NSString *imgName = imgs[i];
                    if(imgName.length)
                    {
                        UIImageView *imgView = [RanTool imgViewWithMode:1 radius:0 imgName:imgs[i]];
                        [view addSubview:imgView];
                        [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
                            make.center.mas_equalTo(0);
                            make.width.mas_equalTo(Zoom(17));
                            make.height.mas_equalTo(Zoom(14));
                        }];
                    }
                    view;
                }) withHeight:Zoom(38) width:Zoom(38) top:0 bottom:CGFLOAT_MIN left:0 right:0 centerX:1];
                [view view_addView:[RanTool labelWithFontSize:Zoom(13) weight:0 color:@"#454545" align:1 text:names[i]] withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:CGFLOAT_MIN bottom:0 left:0 right:0 centerX:0];
                view;
            }) withHeight:CGFLOAT_MIN width:kRBMainScreenWidth/imgs.count top:0 bottom:0 left:0 right:CGFLOAT_MIN centerY:0];
        }
        view;
    });
    [self.view addSubview:statusView];
    [statusView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(kRBStatusBarHeight + kRBNavigationBarHeight + Zoom(30));
        make.height.mas_equalTo(Zoom(67));
    }];
    UIScrollView *scrollView = UIScrollView.new;
    [self.view addSubview:scrollView];
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(kRBStatusBarHeight + kRBNavigationBarHeight + Zoom(140));
    }];
    [scrollView rbSetContentWidth:kRBMainScreenWidth];
    [scrollView addView:({
        UIView *view = UIView.new;
        view.backgroundColor = UIColor.whiteColor;
        [view rbSetCorner:UIRectCornerTopLeft | UIRectCornerTopRight radius:Zoom(15)];
        [view view_addView:[RanTool labelWithFontSize:Zoom(18) weight:2 color:@"333333" align:1 text:@"请下载文件，签字盖章后上传照片"] withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:Zoom(44) bottom:CGFLOAT_MIN left:Zoom(0) right:Zoom(0) centerX:NO];
        [view view_addView:({
            UIView *view = UIView.new;
            [view h_view_addView:[RanTool labelWithFontSize:Zoom(16) weight:0 color:@"#999999" align:0 text:@"合同文件"] withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:0 bottom:0 left:0 right:CGFLOAT_MIN centerY:0];
            [view h_view_addView:({
                UILabel *view = [RanTool labelWithFontSize:Zoom(16) weight:0 color:UIColor.whiteColor align:1 text:@"点击下载" bgColor:@"#518CFF" radius:Zoom(3)];
                [view rbAddTapGesWithTarget:self action:@selector(downloadBtnTapped)];
                view;
            }) withHeight:Zoom(31) width:Zoom(97) top:0 bottom:0 left:CGFLOAT_MIN right:0 centerY:0];
            view;
        }) withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:Zoom(35) bottom:0 left:Zoom(24) right:Zoom(24) centerX:0];
        
        self.photoContainer = [RBGrowablePhotoContainer viewWithMaxNum:100 colNum:2 editable:YES viewWidth:Zoom(200)];
        [view view_addView:({
            UIView *view = UIView.new;
            [view h_view_addView:[RanTool labelWithFontSize:Zoom(16) weight:0 color:@"999999" align:2 text:@"合同照片"] withHeight:CGFLOAT_MIN width:Zoom(87) top:Zoom(10) bottom:CGFLOAT_MIN left:0 right:0 centerY:0];
            [view h_view_addView:self.photoContainer withHeight:self.photoContainer.viewHeight width:Zoom(200) top:0 bottom:0 left:Zoom(30) right:0 centerY:0];

            view;
        }) withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:Zoom(44) bottom:0 left:0 right:CGFLOAT_MIN centerX:0];

        [view view_addView:({
            UILabel *view = [RanTool labelWithFontSize:Zoom(18) weight:0 color:UIColor.whiteColor align:1 text:@"提交" bgColor:@"#518CFF" radius:Zoom(22)];
            [view rbAddTapGesWithTarget:self action:@selector(submitBtnTapped)];
            view;
        }) withHeight:Zoom(44) width:Zoom(314) top:Zoom(100) bottom:Zoom(40) left:0 right:0 centerX:1];
        view;
    }) withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:0 bottom:0 left:0 right:0 centerX:0];
}

#pragma mark - Network

- (void)getData {
    MJWeakSelf;
    [self viewLoadDataWithParam:^(NSMutableDictionary *dicM) {
            
    } path:@"api/contract" post:YES log:YES responseClass:RBShopApplyContractResponse.class desView:self.view showHud:YES showPlaceHolder:NO sucBlock:^(RBShopApplyContractResponse *data) {
        weakSelf.contract_path = data.data.fileurl;
    } failBlock:^(id data) {
        
    } reloadBlock:^{
        
    }];
}

#pragma mark - Event

- (void)downloadBtnTapped
{
    if (self.contract_path == nil && self.contract_path.length == 0) {
        [self.view showTip:@"合同暂不可用" completion:nil];
        return;
    }
    __weak typeof(self) weak_self = self;
    NSString *path = self.contract_path;
    path = [RBURLConfig adjustImageUrl:path];
    NSURL *url = [NSURL fileURLWithPath:path];
    if(!url)
    {
        [self.view showTip:@"合同暂不可用" completion:nil];
        return;
    }
    [weak_self.view showProgressWithText:nil];
    [[NSURLSession.sharedSession downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        [NSOperationQueue.mainQueue addOperationWithBlock:^{
            [weak_self.view hideHud];
            weak_self.document = [UIDocumentInteractionController interactionControllerWithURL:url];
            [weak_self.document presentOpenInMenuFromRect:weak_self.view.bounds inView:weak_self.view animated:YES];
        }];
    }] resume];
}

- (void)submitBtnTapped
{
    __weak typeof(self) weak_self = self;
    if(!self.photoContainer.photos.count)
    {
        [self.view showTip:@"请上传合同照片" completion:nil];
        return;
    }
    
    [self.uploadTool uploadData:({
        NSMutableArray *arrayM = NSMutableArray.array;
        NSArray *imgs = self.photoContainer.photos;
        for (UIImage *img in imgs)
        {
            RBUploadModel *model = RBUploadModel.new;
            model.source = img;
            [arrayM addObject:model];
        }
        arrayM;
    }) withCompletion:^(NSArray *data) {
        NSMutableArray *arrayM = NSMutableArray.array;
        for (RBUploadModel *model in data)
        {
            [arrayM addObject:model.res];
        }
        [weak_self commitWithImgs:arrayM];
    }];
}

- (void)commitWithImgs: (NSArray *)imgs
{
    __weak typeof(self) weak_self = self;
    [self viewLoadDataWithParam:^(NSMutableDictionary *dicM) {
        dicM[@"store_id"] = self.response.data.store_id;
        dicM[@"fileurl"] = [imgs componentsJoinedByString:@","];
    } path:@"han_store_step4" post:YES log:YES responseClass:RBResponse.class desView:self.view showHud:YES showPlaceHolder:NO sucBlock:^(RBResponse *data) {
        [weak_self.view showTip:@"信息已提交,请等待审核" completion:^{
            [weak_self.navigationController popViewControllerAnimated:YES];
        }];
    } failBlock:^(RBResponse *data) {
        [weak_self.view showTip:data.message completion:nil];
    } reloadBlock:nil];
}

#pragma mark - Delegate

- (UIViewController*)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController*)controller
{
    return self;
}

- (UIView*)documentInteractionControllerViewForPreview:(UIDocumentInteractionController*)controller
{
    return self.view;
}

- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController*)controller
{
    return self.view.frame;
}

//点击预览窗口的“Done”(完成)按钮时调用

- (void)documentInteractionControllerDidEndPreview:(UIDocumentInteractionController*)controller
{

}

// 文件分享面板弹出的时候调用

- (void)documentInteractionControllerWillPresentOpenInMenu:(UIDocumentInteractionController*)controller
{
}

// 当选择一个文件分享App的时候调用

- (void)documentInteractionController:(UIDocumentInteractionController*)controller willBeginSendingToApplication:(nullable NSString*)application
{
 NSLog(@"begin send : %@", application);
}

// 弹框消失的时候走的方法

-(void)documentInteractionControllerDidDismissOpenInMenu:(UIDocumentInteractionController*)controller
{
 NSLog(@"dissMiss");
}

#pragma mark - Setter

#pragma mark - Getter

- (RBNavigationBar *)navigationBar
{
    if (!_navigationBar)
    {
        self.navigationBar = ({
            RBNavigationBar *bar = RBNavigationBar.new;
            bar.needGradientView = NO;
            [self.view addSubview:bar];
            [bar mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.top.right.mas_equalTo(0);
                make.height.mas_equalTo(kRBStatusBarHeight + kRBNavigationBarHeight);
            }];
            [bar.naviBar addBackBtnWithWidth:70 image:[UIImage imageNamed:@"backBlack"]];
            {
                UILabel *view = [RanTool labelWithFontSize:18 weight:0 color:@"222222" align:0 text:@"合同审核"];
                [bar.naviBar addSubview:view];
                [view mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.center.mas_equalTo(0);
                }];
            }
            bar;
        });
    }
    return _navigationBar;
}

- (RBUploadTool *)uploadTool
{
    if(!_uploadTool)
    {
        self.uploadTool = RBUploadTool.new;
    }
    return _uploadTool;
}

@end
